<template>
  <Top :loading="loading" @click="topHandler" />
  <div v-loading="loading" class="editor">
    <Left class="left" />
    <Center ref="wrapper" class="center" />
    <Right class="right" />
  </div>
</template>

<script lang="ts" setup>
  import Left from './components/left.vue'
  import Center from './components/center.vue'
  import Right from './components/right.vue'
  import Top from './components/top.vue'
  import { gettemp, savetemp } from '@/api/tag'
  import { useEleStore } from '@/store/modules/coms'
  import router from '@/router'
  import html2canvas from 'html2canvas'

  const route = useRoute()
  const type = ref('add')
  // console.log(router.currentRoute.value.matched[0])
  const init = () => {
    if (route.query && route.query.ID) {
      type.value = 'editor'
      getTemp(route.query.ID)
    } else {
      setEditorData({
        etCode: '',
        etName: '',
        lcdType: '',
        eslWidth: 400,
        eslHeight: 300,
        x0: 0,
        y0: 0,
        remark: '',
        enabled: false,
        companyId: '',
        departmentId: '',
        image: '',
        blockStatus: '',
        parentID: '',
        blockAddColor: '00',
        pathImg: '',
      })
    }
  }
  const { setEditorData, setWidgets, clearWidgets } = useEleStore()
  const { getWidgets, getEditorData } = storeToRefs(useEleStore())
  const loading = ref(false)
  // 获取模板数据
  const getTemp = async (id: any) => {
    loading.value = true
    const { data: data } = await gettemp({ id })
    loading.value = false
    const editorData = data.data || {}
    editorData.eslHeight = editorData.eslHeight - 0 || 300
    editorData.eslWidth = editorData.eslWidth - 0 || 400
    editorData.x0 = editorData.x0 - 0 || 0
    editorData.y0 = editorData.y0 - 0 || 0
    try {
      JSON.parse(editorData.json)
      setWidgets(JSON.parse(editorData.json))
    } catch (e) {
      setWidgets([])
    }
    await setEditorData(editorData)
    console.log(editorData)
  }
  init()

  const topHandler = (type: string) => {
    if (type === 'save') save()
    if (type === 'createImg') createImg()
    if (type === 'clear') clear()
  }

  const save = async () => {
    loading.value = true
    const editorData = dealData()
    console.log(editorData)
    // const { code, message } = await savetemp(editorData)
    // if (code == 200) {
    //   ElMessage({
    //     message: message,
    //     type: 'success',
    //   })
    //   router.back()
    // }
    // 保存模板数据
    getCanvas()
      .then(async (data) => {
        editorData.image = data
        const { code, message } = await savetemp(editorData)
        loading.value = false
        if (code == 200) {
          ElMessage({
            message: message,
            type: 'success',
          })
          router.push({ path: '/eslstock/templateList' })
        }
      })
      .catch(() => {
        loading.value = false
      })
  }
  const dealData = () => {
    const editorData = JSON.parse(JSON.stringify(getEditorData.value))
    editorData.eslHeight += ''
    editorData.eslWidth += ''
    editorData.x0 += ''
    editorData.y0 += ''
    editorData.json = JSON.stringify(getWidgets.value)
    return editorData
  }
  const $baseConfirm = inject('$baseConfirm') as any
  const clear = () => {
    $baseConfirm('确定要清空所有组件吗', '提示', async () => {
      clearWidgets()
    })
  }

  // 生成图片
  const wrapper = ref(null) as any
  const getCanvas = () => {
    return new Promise((resolve) => {
      nextTick(() => {
        html2canvas(wrapper.value.getListWapper().value, {
          logging: false,
          allowTaint: true,
          // scale: 3,
          // scale: window.devicePixelRatio,
          // width: shareContent.clientWidth, //dom 原始宽度
          // height: shareContent.clientHeight,
          scrollY: 0,
          scrollX: 0,
          useCORS: true,
          backgroundColor: '#ffffff',
        }).then(function (canvas: any) {
          const imgUrl = canvas.toDataURL('image/png')
          resolve(imgUrl)
        })
      })
    })
  }
  // 转为base64图片
  // const getBase64Image = (img: any) => {
  //   const canvas = document.createElement('canvas')
  //   canvas.width = img.width
  //   canvas.height = img.height
  //   const ctx: any = canvas.getContext('2d')
  //   ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
  //   const dataURL = canvas.toDataURL('image/png') // 可选其他值 image/jpeg
  //   return dataURL
  // }
  // const getCanvas = () => {
  //   return new Promise((resolve) => {
  //     nextTick(() => {
  //       const htmlContainer = wrapper.value.getListWapper().value // 需要截图的包裹的（原生的）DOM 对象
  //       const width = htmlContainer.offsetWidth // 获取dom 宽度
  //       const height = htmlContainer.offsetHeight // 获取dom 高度
  //       const canvas: any = document.createElement('canvas') // 创建一个canvas节点
  //       const scale = 2 // 定义任意放大倍数 支持小数
  //       canvas.width = width * scale // 定义canvas 宽度 * 缩放
  //       canvas.height = height * scale // 定义canvas高度 *缩放
  //       canvas.getContext('2d').scale(scale, scale) // 获取context,设置scale
  //       let imgs = htmlContainer.querySelectorAll('img')
  //       let count = 0 // 计数用
  //       // 排除base64图片，因为base64图片不会有跨域问题
  //       imgs = Array.from(imgs).filter((elem: any) => {
  //         return !/^data:image\/png;base64/.test(elem.src)
  //       })
  //       console.log(imgs)
  //       imgs.forEach((elem: any, index: number, arr: any) => {
  //         const image: any = new Image()
  //         image.crossOrigin = 'anonymous' // 支持跨域图片
  //         image.src = elem.src
  //         image.onload = () => {
  //           elem.src = getBase64Image(image)
  //           count++
  //           // 全部图片加载完毕
  //           if (count === arr.length) {
  //             html2canvas(wrapper.value.getListWapper().value, {
  //               logging: false,
  //               allowTaint: true,
  //               scale: 2,
  //               // scale: window.devicePixelRatio,
  //               // width: shareContent.clientWidth, //dom 原始宽度
  //               // height: shareContent.clientHeight,
  //               scrollY: 0,
  //               scrollX: 0,
  //               useCORS: true,
  //               backgroundColor: '#ffffff',
  //             }).then(function (canvas: any) {
  //               const imgUrl = canvas.toDataURL('image/png')
  //               resolve(imgUrl)
  //             })
  //           }
  //         }
  //       })
  //     })
  //   })
  // }
  const createImg = async () => {
    const imgUrl: any = await getCanvas()
    const tempLink: any = document.createElement('a') // 创建一个a标签
    tempLink.style.display = 'none'
    tempLink.href = imgUrl
    tempLink.setAttribute('download', '标签') // 给a标签添加下载属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    document.body.appendChild(tempLink) // 将a标签添加到body当中
    tempLink.click() // 启动下载
    document.body.removeChild(tempLink) // 下载完毕删除a标签
    window.URL.revokeObjectURL(imgUrl)
  }
</script>

<style lang="scss" scoped>
  .editor {
    display: flex;
    overflow: auto;
    padding-top: 0 !important;
    padding: 0;
    // justify-content: space-between;
  }

  .operation {
    display: flex;
    justify-content: flex-end;
    height: 40px;
    align-items: center;

    .save {
      margin-right: 80px;
    }

    .clear {
      margin-right: 10px;
    }
  }
</style>
